package br.com.amigooo.services;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import br.com.amigooo.model.User;

public class HttpRetriever extends AsyncTask<Map<String, User>, Void, String>{

	static DefaultHttpClient httpclient = new DefaultHttpClient();
	static HttpPost httpost = null;

	@Override
	protected String doInBackground(Map<String, User>... params) {
		Map<String, User> mp = params[0];
		User user = null;
		String url = null;
		
		for(String key : mp.keySet()){
			url = key;
			user = mp.get(key);
			break;
		}
		
		httpost = new HttpPost(url);

		HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
		HttpResponse response;
		JSONObject holder = new JSONObject();
		StringBuffer sb = new StringBuffer();

		try {
			holder.put("email", user.getEmail());
			holder.put("name", user.getName());
			holder.put("userPassword", user.getUserPassword());

			StringEntity se = new StringEntity(holder.toString());
			se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));

			httpost.setEntity(se);
			response = httpclient.execute(httpost);

			if (response != null) {
				String line;
				BufferedReader br = null;
				InputStream in = response.getEntity().getContent();

				br = new BufferedReader(new InputStreamReader(in));
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	protected void onPostExecute(String str) {
        if(str != null){
        	System.out.println(str);
        }
    }

}
